<?php

namespace Encore\Admin\Console;

use Illuminate\Console\GeneratorCommand;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;

class ServiceCommand extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin:service {name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Make a service';

    public function handle()
    {
        //judge if the service's directory exists
        $servicePath = config('admin.service_path', base_path('services'));

        if (!is_dir($servicePath)) {
            (new Filesystem())->makeDirectory($servicePath, 0755, true);
        }

        $name = $this->argument('name');

        //judge if the name has directory
        if (Str::contains($name, '/')) {
            $directory = dirname($name);
            //credit directory in service's directory
            if (!is_dir($servicePath . '/' . $directory)) {
                (new Filesystem())->makeDirectory($servicePath . '/' . $directory, 0755, true);
            }
            $servicePath .= '/' . $directory;
        }


        $className = Str::studly(Str::afterLast($name, '/'));
        //class name must contain 'Service'
        !Str::contains($className, 'Service') && $className .= 'Service';

        //get stub service file
        $stub = file_get_contents($this->getStub());
        //replace the stub's DummyClass with the service's name
        $stub = str_replace('DummyClass', $className, $stub);
        //replace the stub's DummyNamespace with the service's namespace
        if (Str::contains($name, '/')) {
            $directory = str_replace('/', '\\', Str::beforeLast($name, '/'));
            $stub = str_replace('DummyNamespace', config('admin.service_namespace', 'Services') . '\\' . $directory, $stub);
        } else {
            $stub = str_replace('DummyNamespace', config('admin.service_namespace', 'Services'), $stub);
        }

        //file path
        $filePath = $servicePath . '/' . $className . '.php';

        //judge if the service file exists
        if (file_exists($filePath)) {
            $this->error('Service file already exists!');
            return;
        }

        //create the service file
        file_put_contents($filePath, $stub);

        $this->info('Service created successfully.');
    }

    protected function getStub(): string
    {
        return __DIR__ . '/stubs/service.stub';
    }
}
